const express = require('express')
const http = require('http')
const WebSocket = require('ws')
const Redis = require('ioredis')
const config = require('./config')
const redis = new Redis(config.redis)
const realIp = require('express-real-ip')()
const path = require('path')
const request = require('request-promise')
const log4js = require('log4js')

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('Websocket服务器')

const app = express()
const server = http.createServer(app)
const wss = new WebSocket.Server({server})

// 获取客户端ip
app.use(realIp)
// 静态文件
app.use(express.static(path.join(__dirname, 'public')))

// 接收到连接
wss.on('connection', (ws, req) => {
  ws.isAlive = true
  ws.on('pong', function () {
    this.isAlive = true
  })
  console.log('receive a new connection: ' + getClientIp(req))

  ws.on('message', message => {
    console.log('received: %s', message)
  })
  ws.send('hello, client!')
})

// 每30秒ping一次
setInterval(() => {
  wss.clients.forEach(ws => {
    if (ws.isAlive === false) {
      return ws.terminate()
    }
    ws.isAlive = false
    ws.ping(() => { })
  })
}, 30000)

// 广播
wss.broadcast = (data) => {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data)
    }
  })
}

server.listen(8080, () => {
  console.log('server listening on %d', server.address().port)
})

redis.subscribe('news')
redis.on('message', async (channel, message) => {
  console.log('Receive message from redis: ' + message + '\n')
  channel === 'news' && wss.broadcast(message)
  channel === 'news' && await request({
    method: 'POST',
    url: 'http://push.cthai.cn/weixin/index/index',
    body: {message: message},
    json: true
  }).catch(e => {logger.error(e)})
})

function getClientIp (req) {
  return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
}
